<?php

namespace App\Lib\Rooms\Services;

use App\Lib\_Error\ExecuteException;
use App\Lib\_Validator\RoomValidator;
use App\Lib\LibBaseService;
use App\Lib\Rooms\Events\RoomCreatedEvent;
use App\Model\RoomsModel;
use App\Model\UsersModel;

class RoomService extends LibBaseService
{


    /**
     * 创建房间
     * @param UsersModel $renter
     * @param array $data
     * @param UsersModel|null $owner
     * @return RoomsModel
     * @throws ExecuteException
     */
    public function create(UsersModel $renter, array $data, UsersModel $owner = null)
    {
        RoomValidator::create($data);

        $room = new RoomsModel([
            'owner' => is_null($owner) ? $renter->id : $owner->id,
            'rent_uid' => $renter->id,
        ]);
        if (!$room->fill($data)->save()) {
            throw new ExecuteException('创建房间失败');
        }
        $this->eventDispatcher->dispatch(new RoomCreatedEvent($room, $owner ?? $renter, $renter));
        return $room;

    }
}